<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body{
            margin: 0;
            padding: 0;

        }
        #div1{
            width: 100px;
            height: 100px;
            background: skyblue;
            position: absolute;
            top:0;
        }
        #div2{
            width: 500px;
            height: 500px;
            background: #ccc;
            position: relative;
        }
    </style>
</head>
<body>
  <div id="div2">
  <div id="div1"></div>
  </div>
  <script>
      var oDiv = document.getElementById('div1');
      var oDiv2 = document.getElementById('div2');

      var disX = 0;
      var disY =0;
      oDiv.onmousedown = function (ev) {
         var oEvent = ev || event;
         disX = oEvent.clientX - oDiv.offsetLeft;
         disY = oEvent.clientY - oDiv.offsetTop;
          document.onmousemove = function (ev) {//拖拽的行为发生在onmousedown里面
              var oEvent = ev || event;

              var left = oEvent.clientX-disX;
              var top = oEvent.clientY-disY;

              if(left<50){ //用户体验
                  left=0;
              }
              else if(left>oDiv2.offsetWidth-oDiv.offsetWidth){//继续向右边滑动的时候就不是oDiv.style.width了，而是offsetWidth
                  left=oDiv2.offsetWidth-oDiv.offsetWidth
              }
              if (top<50){
                  top = 0;
              }
              else if(top>oDiv2.offsetHeight-oDiv.offsetHeight){
                  top=oDiv2.offsetHeight-oDiv.offsetHeight;
              }
              oDiv.style.left =left +'px';
              oDiv.style.top = top+'px';



          };
          document.onmouseup = function () {
              document.onmousemove= null;
              document.onmouseup = null;
          };

          return false;//阻止火狐的默认事件---鼠标按下的时候会自动创建一个新的div
      };
  </script>
</body>
</html>